package com.example.wac.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.example.wac.annotation.UnJwtToken;
import com.example.wac.service.LoginService;
import com.example.wac.vo.ApiResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author wuancheng
 * @description 常用于运管等需要账号密码的登录
 * @date 2022-04-24 17:43:00
 */

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    LoginService loginService;

    @UnJwtToken
    @GetMapping("/captcha")
    public void getCaptcha (HttpServletRequest request, HttpServletResponse response) throws IOException {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        captcha.write(response.getOutputStream());
    }

    /**
     * 用户登录
     * @param dto
     * @param request
     * @return
     */
    @UnJwtToken
    @PostMapping("/login")
    public ApiResult login(@RequestBody Map<String, Object> dto, HttpServletRequest request){
        return loginService.login(dto, request);
    }

    @UnJwtToken
    @GetMapping("/logout")
    public ApiResult logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            subject.logout();
            return ApiResult.success(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN) + "成功退出");
        }else {
            return ApiResult.error(null, "您尚未登录");
        }
    }

    /**
     * 需要开启免token 否则未认证跳转该controller失败
     *
     * @return
     */
    @UnJwtToken
    @GetMapping("/login_return")
    public ApiResult loginReturn(){
        return ApiResult.error(null,"您尚未登录");
    }

    /**
     * 需要开启免token 否则未授权跳转该controller失败
     *
     * @return
     */
    @UnJwtToken
    @GetMapping("/authorize_return")
    public ApiResult authorizeReturn(){
        return ApiResult.error(null,"当前没有访问权限");
    }
}
